package com.lmxdawn.api.admin.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.alipay.api.AlipayApiException;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lmxdawn.api.admin.annotation.AuthRuleAnnotation;
import com.lmxdawn.api.admin.entity.Training;
import com.lmxdawn.api.admin.entity.auth.AuthAdmin;
import com.lmxdawn.api.admin.req.ExtraPageRequest;
import com.lmxdawn.api.admin.req.ListPageRequest;
import com.lmxdawn.api.admin.service.ITrainingService;
import com.lmxdawn.api.admin.service.auth.AuthAdminService;
import com.lmxdawn.api.common.res.BaseResponse;
import com.lmxdawn.api.common.util.ResultVOUtils;
import com.lmxdawn.api.dnf.entity.ExtraApply;
import com.lmxdawn.api.dnf.entity.Order;
import com.lmxdawn.api.dnf.entity.RealName;
import com.lmxdawn.api.dnf.entity.WithdrawAccount;
import com.lmxdawn.api.dnf.service.IExtraApplyService;
import com.lmxdawn.api.dnf.service.IRealnameService;
import com.lmxdawn.api.dnf.service.impl.WithdrawAccountServiceImpl;
import lombok.val;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * <p>
 * 代练服务 前端控制器
 * </p>
 *
 * @author huangyubin
 * @since 2024-07-05
 */
@RestController
@RequestMapping("/admin/dnf/extraApply")
public class ExtraApplyController {

    @Resource
    IExtraApplyService applyService;

    @Resource
    AuthAdminService adminService;
    @Resource
    IRealnameService realnameService;
    @Autowired
    private WithdrawAccountServiceImpl withdrawAccountServiceImpl;

    @PostMapping("/page")
    @AuthRuleAnnotation("admin/dnf/extraApply/page")
    public BaseResponse page(@Valid @RequestBody ExtraPageRequest pageRequest) {
        String timeStart = CollUtil.isNotEmpty(pageRequest.getApplyTime()) ? pageRequest.getApplyTime().get(0) : "";
        String timeEnd = CollUtil.isNotEmpty(pageRequest.getApplyTime()) ? pageRequest.getApplyTime().get(1) : "";

        val page = applyService.page(Page.of(pageRequest.getPage(), pageRequest.getLimit()),
        Wrappers.<ExtraApply>lambdaQuery()
                .between(CollUtil.isNotEmpty(pageRequest.getApplyTime()), ExtraApply::getCreateTime, timeStart, timeEnd )
                .orderByDesc(ExtraApply::getCreateTime));
        val records = page.getRecords();
        if (CollUtil.isEmpty(records)){
            return ResultVOUtils.success(page);
        }
        Set<String> account = records.stream().map(ExtraApply::getAccount).collect(Collectors.toSet());
        List<WithdrawAccount> accounts = withdrawAccountServiceImpl.lambdaQuery().in(WithdrawAccount::getId, account).list();
        Map<String, WithdrawAccount> accountMap = accounts.stream().collect(Collectors.toMap(w->w.getId().toString(), Function.identity()));
        Set<String> userSet = records.stream().map(ExtraApply::getUserId).collect(Collectors.toSet());
        List<AuthAdmin> userList = adminService.listByIds(userSet);
        List<RealName> realNameList = realnameService.lambdaQuery().in(RealName::getUserId, userSet).list();
        Map<String, String> map2 = realNameList.stream().collect(Collectors.toMap(RealName::getUserId, RealName::getRealname));
        Map<String, AuthAdmin> map = userList.stream().collect(Collectors.toMap(AuthAdmin::getId, Function.identity()));
        for (ExtraApply record : records) {
            record.setUserName(map.get(record.getUserId()).getUsername());
            record.setRealName(map2.get(record.getUserId()));
            WithdrawAccount withdrawAccount = accountMap.get(record.getAccount());
            if (withdrawAccount == null){
                continue;
            }
            record.setAccount(withdrawAccount.getAccount());
            record.setAccountId(map.get(record.getUserId()).getCode());
            record.setAccountType(StrUtil.equals("1", withdrawAccount.getAccountType()) ? "支付宝": "微信");
        }
        return ResultVOUtils.success(page);
    }

    @PostMapping("/pass")
    @AuthRuleAnnotation("admin/dnf/extraApply/pass")
    public BaseResponse pass(@Valid @RequestBody ExtraApply apply, HttpServletRequest request) throws AlipayApiException {
        String id = request.getHeader("X-Adminid");

        ExtraApply res = applyService.doExtra(apply, id);
        if (Objects.equals(res.getRes(), 1) || apply.getStatus() == 2){
            return ResultVOUtils.success();
        }else{
            return ResultVOUtils.error(500, res.getRemark());
        }
    }

    @PostMapping("/save")
    @AuthRuleAnnotation("admin/dnf/extraApply/save")
    public BaseResponse save(@Valid @RequestBody ExtraApply apply) {
        return ResultVOUtils.success(applyService.save(apply));
    }

    @PostMapping("/edit")
    @AuthRuleAnnotation("admin/dnf/extraApply/edit")
    public BaseResponse edit(@Valid @RequestBody ExtraApply apply) {
        return ResultVOUtils.success(applyService.updateById(apply));
    }

    @PostMapping("/delete")
    @AuthRuleAnnotation("admin/dnf/extraApply/delete")
    public BaseResponse delete(@Valid @RequestBody ExtraApply apply) {
        return ResultVOUtils.success(applyService.removeById(apply));
    }
}
